package goshp

import (
	"os"
	"io"
)

// append data[]byte to slice and returns the new byte slice
func Append(slice, data []byte) []byte {
	l := len(slice)
	if l+len(data) > cap(slice) { // reallocate
		// Allocate double what's needed, for future growth.
		// increase capcity %20
		cap := l+len(data)*(5/4)
		newSlice := make([]byte, cap)
		//newSlice := make([]byte, (l+len(data))*2)
		// The copy function is predeclared and works for any slice type.
		copy(newSlice, slice)
		slice = newSlice
	}
	slice = slice[0 : l+len(data)]
	for i, c := range data {
		slice[l+i] = c
	}
	return slice
}

func ReadFile(filename string) ([]byte, os.Error) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	d, err := f.Stat()
	if err != nil {
		return nil, err
	}
	buf := make([]byte, d.Size)
	_, err = io.ReadFull(f, buf)
	if err != nil {
		return nil, err
	}
	return buf, err
}


func ToBytes(x uint32) []byte {
	var buf [4]byte
	buf[0] = byte(x >> 0)
	buf[1] = byte(x >> 8)
	buf[2] = byte(x >> 16)
	buf[3] = byte(x >> 24)
	return buf[:]
}

func Int32bytes(x int32) []byte {
	var buf [4]byte
	buf[0] = byte(x >> 0)
	buf[1] = byte(x >> 8)
	buf[2] = byte(x >> 16)
	buf[3] = byte(x >> 24)
	return buf[:]
}

func Uint32bytes(x uint32) []byte {
	var buf [4]byte
	buf[0] = byte(x >> 0)
	buf[1] = byte(x >> 8)
	buf[2] = byte(x >> 16)
	buf[3] = byte(x >> 24)
	return buf[:]
}


func Uint64bytes(x uint64) []byte {
	var buf [8]byte
	buf[0] = byte(x >> 0)
	buf[1] = byte(x >> 8)
	buf[2] = byte(x >> 16)
	buf[3] = byte(x >> 24)
	buf[4] = byte(x >> 32)
	buf[5] = byte(x >> 40)
	buf[6] = byte(x >> 48)
	buf[7] = byte(x >> 56)
	
	return buf[:]
}


func Int64bytes(x uint64) []byte {
	var buf [8]byte
	buf[0] = byte(x >> 0)
	buf[1] = byte(x >> 8)
	buf[2] = byte(x >> 16)
	buf[3] = byte(x >> 24)
	buf[4] = byte(x >> 32)
	buf[5] = byte(x >> 40)
	buf[6] = byte(x >> 48)
	buf[7] = byte(x >> 56)
	
	return buf[:]
}